﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Toybox.CookieGetterSharp.SQLite
{
  class GoogleChromeBrowserManager : IBrowserManager
  {
    const string USERDATAPATH = @"%LOCALAPPDATA%\Google\Chrome\User Data";
    const string LOCALSTATE = @"Local State";
    const string COOKIES = @"Cookies";

    #region IBrowserManager メンバ

    public BrowserType BrowserType
    {
      get { return BrowserType.GoogleChrome; }
    }

    public ICookieGetter CreateDefaultCookieGetter()
    {
      GoogleChromeProfile profile = GoogleChromeProfile.GetDefaultProfile(Utility.ReplacePathSymbols(USERDATAPATH), LOCALSTATE);
      return CreateCookieGetter(profile);
    }

    public ICookieGetter[] CreateCookieGetters()
    {
      GoogleChromeProfile[] profiles = GoogleChromeProfile.GetProfiles(Utility.ReplacePathSymbols(USERDATAPATH), LOCALSTATE);

      if (profiles.Length == 0)
      {
        return new ICookieGetter[] { CreateCookieGetter(new GoogleChromeProfile()) };
      }

      ICookieGetter[] cgs = new ICookieGetter[profiles.Length];
      for (int i = 0; i < profiles.Length; i++)
      {
        cgs[i] = CreateCookieGetter(profiles[i]);
      }
      return cgs;
    }
    #endregion

    private ICookieGetter CreateCookieGetter(GoogleChromeProfile profile)
    {
      string name = "GoogleChrome";
      string path = null;

      if (profile != null)
      {
        if (!string.IsNullOrEmpty(profile.Name))
          name += " " + profile.Name;
        path = System.IO.Path.Combine(new string[] { Utility.ReplacePathSymbols(USERDATAPATH), profile.Path, COOKIES });
      }

      CookieStatus status = new CookieStatus(name, path, this.BrowserType, PathType.File);
      return new GoogleChromeCookieGetter(status);
    }
  }
}
